<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      canvas {
        border: 1px solid #ccc;
        margin-right:5px;
      }
    </style>
  </head>
  <body>
    <div>
      <button>下载canvas1</button>
      <button>下载canvas3</button>
    </div>
    <script>
      let canvas1 ;
      let canvas3 ;
      (() => {
        canvas1 = document.createElement("canvas");
        canvas1.width = 200;
        canvas1.height = 200;
        document.body.append(canvas1);

        const ctx = canvas1.getContext('2d');
       
        //同心圆
        for(let i = 1;i<=5;i++){
          ctx.beginPath();
          ctx.arc(100 , 100 , 20*i , 0 , Math.PI * 2);
          ctx.stroke();
        }

        ctx.beginPath();
        ctx.moveTo(0,100)
        ctx.lineTo(200,100);
        ctx.stroke();

        
        ctx.beginPath();
        ctx.moveTo(100,0)
        ctx.lineTo(100,200);
        ctx.stroke();

      })();

      (() => {
        const canvas = document.createElement("canvas");
        canvas.width = 400;
        canvas.height = 400;
        document.body.append(canvas);

        const ctx = canvas.getContext('2d');
       
        ctx.drawImage(canvas1,0,0,100,100 , 150,150,100,100);

      })();


      (() => {
        const btn = document.querySelector('button') ;
        btn.onclick = function(){
          const url = canvas1.toDataURL();
          const a = document.createElement('a');
          a.href = url ;
          a.download = 'canvas画布' ;
          a.click();
        }
      })();

      
      (() => {
        const canvas = document.createElement("canvas");
        canvas3 = canvas ;
        canvas.width = 400;
        canvas.height = 400;
        document.body.append(canvas);

        const ctx = canvas.getContext('2d');
       
        const img = new Image();
        img.crossOrigin = 'anonymous';
        img.src = '../imgs/01.png';
        img.onload = function(){
          ctx.drawImage(img,0,0);
        }

      })();

      (() => {
        const btn = document.querySelectorAll('button')[1] ;
        btn.onclick = function(){
          const url = canvas3.toDataURL();
          const a = document.createElement('a');
          a.href = url ;
          a.download = 'canvas画布' ;
          a.click();
        }
      })();


      
      
    </script>
  </body>
</html>
